package com.test.mybatis.generator;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializeFilter;
import com.alibaba.fastjson.serializer.SerializerFeature;

import java.io.*;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.util.*;

/**
 * @author HelSing
 * @date 2019/3/18
 */
public class VueCommentGenerator {
    //只需要改动这里;
    private static String database = "japan";
    private static String className = "com.mysql.jdbc.Driver";

    private static String username = "aojiroot";
    private static String password = "Aoji@321.com";

    private static String url = "jdbc:mysql://bj-cdb-lkltxurs.sql.tencentcdb.com:63769/" + database + "?serverTimezone=GMT";

    private static String daoPath = System.getProperty("user.dir").indexOf("/") == -1 ?
      System.getProperty("user.dir").replace("\\", "/") : System.getProperty("user.dir");


    private static List<String> c = new ArrayList<>();
    static {
        c.add("t_dict");

    }

    public static void main(String[] args) throws Exception {
        front();
    }

    public static void front() throws Exception{
        List<String> cz = new ArrayList<>();
        Class.forName(className);
        Connection connection = DriverManager.getConnection(url, username, password);
        DatabaseMetaData metaData = connection.getMetaData();

        //获取数据库下面所有表
        ResultSet tables = metaData.getTables(database, null, "%", new String[]{"TABLE"});
        int index = 0;
        while (tables.next()) {
            index++;
            // 列的个数
            int columnCount = tables.getMetaData().getColumnCount();
            // 根据指定列名称获取数据
            String TABLE_NAME = tables.getString("TABLE_NAME");
            if (cz.contains(TABLE_NAME)) {
                continue;
            }
            if (!c.isEmpty()) {
                if (!c.contains(TABLE_NAME)) {
                    continue;
                }
            }

            System.out.println(TABLE_NAME);
            cz.add(TABLE_NAME);
            String tableNames = TABLE_NAME.substring(2);
            String head = convertName(tableNames);
            System.out.println(head);
            String h = head.substring(0, 1);

            FileInputStream inputStream = new FileInputStream(daoPath + "/fkdx-dao/src/test/java/com/test/mybatis/generator/vue/vue.text");
            String str = readFile(inputStream);
            str = str.replace("${saveFn}", head+ "Save");
            str = str.replace("${qurl}", head);
            //获取表的所有列
            ResultSet columns = metaData.getColumns(database, "%", TABLE_NAME, "%");

            // 表格
            List<TableHeader> tableList = new ArrayList<TableHeader>();

            // 表单
            List<FromAddColumn> columnList = new ArrayList<FromAddColumn>();
            //校验
            Map<String, List<RulesDetail>> property = new HashMap<>();
            Map<String, Object> formData = new HashMap<>();
            while (columns.next()) {
                String COLUMN_NAME = columns.getString("COLUMN_NAME");
                String COLUMN_NAME_UP = convertName(COLUMN_NAME);
                formData.put(COLUMN_NAME_UP, null);
                String TYPE_NAME = columns.getString("TYPE_NAME");
                String NULLABLE = columns.getString("NULLABLE");
                String REMARKS = columns.getString("REMARKS");
                String COLUMN_SIZE = columns.getString("COLUMN_SIZE");
                String DECIMAL_DIGITS = columns.getString("DECIMAL_DIGITS");
                String p = TYPE_NAME.replace(" UNSIGNED", "");
                if (COLUMN_NAME_UP.equals("created") || COLUMN_NAME_UP.equals("createUser") ||
                  COLUMN_NAME_UP.equals("createUserName") || COLUMN_NAME_UP.equals("modified") ||
                  COLUMN_NAME_UP.equals("modificationUserName") || COLUMN_NAME_UP.equals("modificationUserId")
                  || COLUMN_NAME_UP.equals("yn") || COLUMN_NAME_UP.equals("tenantId")
                ) {
                    continue;
                }
                //添加校验
                if (NULLABLE.equals("0")) {
                    if(!COLUMN_NAME.equals("id")) {
                        List<RulesDetail> d = new ArrayList<>();
                        RulesDetail r = new RulesDetail();
                        d.add(r);
                        String rem[] = REMARKS.split(" ");
                        String text = "请输入";
                        if (rem.length > 1 && REMARKS.contains(":")) {
                            text = "请选择";
                        }
                        r.setRequired(true);
                        r.setMessage(text + rem[0]);
                        if (TYPE_NAME.equals("VARCHAR")) {
                            if (rem.length == 1 && !REMARKS.contains(":")) {
                                RulesDetail r1 = new RulesDetail();
                                r1.setMin(1);
                                r1.setMax(Integer.parseInt(COLUMN_SIZE));
                                r1.setMessage("不能超过 1 到 " + r1.getMax() + " 个字");
                                d.add(r1);
                            }
                        }
                        if (TYPE_NAME.toLowerCase(Locale.ROOT).equals("decimal")) {
                            RulesDetail r2 = new RulesDetail();
                            r2.setPattern("/^[1-9]\\d{0," + COLUMN_SIZE + "}(\\.\\d{1," + DECIMAL_DIGITS + "})?$|^0(\\.\\d{1," + DECIMAL_DIGITS + "})?$/");
                            r2.setMessage("整数位不能超过" + COLUMN_SIZE + ",小数位不能超过" + DECIMAL_DIGITS);
                            d.add(r2);
                        }
                        if (TYPE_NAME.toLowerCase(Locale.ROOT).equals("int")) {
                            RulesDetail r2 = new RulesDetail();
                            r2.setPattern("/^[\\-\\+]?[1-9]\\d*$/");
                            r2.setMessage("请勿包含非法字符");
                            d.add(r2);
                        }
                        property.put(COLUMN_NAME_UP, d);
                    }
                }

                //表格
                TableHeader th = new TableHeader();
                th.setProp(COLUMN_NAME_UP);
                th.setLabel(REMARKS.contains(" ") ? REMARKS.split(" ")[0]: REMARKS);
                if (COLUMN_NAME.equals("id")) {
                    th.setLabel("编码");
                }
                th.setWidth("150");
                tableList.add(th);
                FromAddColumn f = new FromAddColumn();
                f.setField(COLUMN_NAME_UP);
                f.setName(REMARKS.contains(" ") ? REMARKS.split(" ")[0]: REMARKS);
                if (COLUMN_NAME.equals("id")) {
                    f.setName("编码");
                } else if ("DATETIME".equals(TYPE_NAME)) {
                    f.setDate(true);
                    f.setPlaceholder("请选择时间");
                } else if (("BIT".equals(TYPE_NAME) || "TINYINT".equals(TYPE_NAME)) && COLUMN_SIZE.equals("1")) {
                    String strCode[] = REMARKS.split(" ");
                    List<Map<String, String>> selectList = new ArrayList<>();
                    for (int i = 1, l = strCode.length; i < l; i++) {
                        String s = strCode[i];
                        if (s.trim().equals("") || s.trim().equals("默认")){
                            continue;
                        }
                        Map<String, String> m = new HashMap<>();
                        String[] d = s.split(":");
                        if(d.length > 1) {
                            m.put("val", d[0]);
                            m.put("label", d[1]);
                            selectList.add(m);
                        }
                    }
                    f.setSelect(true);
                    f.setSelectData(selectList);
                    th.setDic(selectList);
                }
                if (!COLUMN_NAME.equals("id")) {
                    columnList.add(f);
                }

            }

            str = str.replace("${rules}", JSON.toJSONString(property));



            List<Btn> btns = new ArrayList<>(3);
            TableHeader btn1 = new TableHeader();
            btn1.setProp("btn");
            btn1.setLabel("操作");
            btn1.setWidth("180");
            btn1.setBtn(btns);
            Btn b = new Btn();
            b.setName("查看");
            btns.add(b);
            Btn b1 = new Btn();
            b1.setName("编辑");
            btns.add(b1);
            Btn b2 = new Btn();
            b2.setName("审批");
            btns.add(b2);
            tableList.add(btn1);

            str = str.replace("${bindex}", (tableList.size() - 1) + "");
            str = str.replace("${tableHeader}", JSON.toJSONString(tableList));
            str = str.replace("${fromAddColumn}", JSON.toJSONString(columnList));


            FromAddColumn f = new FromAddColumn();
            f.setBtn(true);
            f.setName("查询");
            f.setType("'primary'");
            f.setIcon("el-icon-search");
            f.setFunc("");
            columnList.add(f);
            str = str.replace("${fromColumn}", JSON.toJSONString(columnList));
            str = str.replace("${qindex}", JSON.toJSONString(columnList.size() - 1));
            str = str.replace("${formData}", JSON.toJSONString(formData,SerializerFeature.WriteMapNullValue));
            System.out.println(str);

            writeFile(str, index + ".ts", "ts");
        }

    }
    private static void writeFile(String str, String fileName, String dir) {
        String filePath = daoPath + "/fkdx-dao/src/test/java/com/test/mybatis/generator/file/" + dir + "/";
        FileWriter fw = null;
        try {

            File file = new File(filePath);
            if (!file.exists()) {
                file.mkdirs();
            }
            File file2 = new File(filePath + fileName);

            if (!file2.exists()) {
                file.createNewFile();
            }
            fw = new FileWriter(filePath + fileName);
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(str);
            bw.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                fw.close();
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }

    private static String readFile(FileInputStream inputStream) throws IOException {

        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

        StringBuilder returnStr = new StringBuilder();

        String str = null;
        while ((str = bufferedReader.readLine()) != null) {
            returnStr.append(str);
        }
        inputStream.close();
        bufferedReader.close();

        return returnStr.toString();
    }

    private static String convertName(String columnName) {
        StringBuilder sb = new StringBuilder();
        String[] str = columnName.split("_");
        sb.append(str[0]);
        for (int i = 1, l = str.length; i < l; i++) {
            String s = str[i];
            sb.append(s.substring(0,1).toUpperCase(Locale.ROOT));
            sb.append(s.substring(1));
        }
        return sb.toString();
    }


    public static void json() throws Exception {
        List<String> cz = new ArrayList<>();
        String url = "jdbc:mysql://rm-8vb43b03vawbw24k0oo.mysql.zhangbei.rds.aliyuncs.com:3306/yfgranary?serverTimezone=GMT";
        String user = "root";
        String password = "Jiajiale5";
        Class.forName("com.mysql.jdbc.Driver");
        Connection connection = DriverManager.getConnection(url, user, password);
        DatabaseMetaData metaData = connection.getMetaData();

        //获取数据库下面所有表
        ResultSet tables = metaData.getTables("yfgranary", null, "%", new String[] { "TABLE" });

        while (tables.next()) {
            // 列的个数
            int columnCount = tables.getMetaData().getColumnCount();
            // 根据指定列名称获取数据
            String TABLE_NAME = tables.getString("TABLE_NAME") ;
            if (cz.contains(TABLE_NAME)) {
                continue;
            }
            if (!c.isEmpty()) {
                if (!c.contains(TABLE_NAME)) {
                    continue;
                }
            }
            System.out.println(TABLE_NAME);
            cz.add(TABLE_NAME);
            // User表  获取表的所有列
            ResultSet columns = metaData.getColumns("yfgranary", "%", TABLE_NAME, "%");

            // 表格
            List<SwaggerHeader> tableList = new ArrayList<SwaggerHeader>();

            // 表单
            List<FromAddColumn> columnList = new ArrayList<FromAddColumn>();
            StringBuilder json = new StringBuilder();
            while (columns.next()) {
                String COLUMN_NAME = columns.getString("COLUMN_NAME");
                COLUMN_NAME = convertName(COLUMN_NAME);
                String TYPE_NAME = columns.getString("TYPE_NAME");
                String REMARKS = columns.getString("REMARKS");
                String COLUMN_SIZE = columns.getString("COLUMN_SIZE");
                if (COLUMN_NAME.equals("yn")) {
                    continue;
                }
                //{"label":"编码","minWidth":"'150px'","prop":"id"};
                //name="mobile",value="手机号",required=true,paramType="form"
                json.append(",\"").append(COLUMN_NAME).append("\":null");
                SwaggerHeader th = new SwaggerHeader();
                th.setName(COLUMN_NAME);
                th.setValue(REMARKS.contains(" ") ? REMARKS.split(" ")[0]: REMARKS);
                if (COLUMN_NAME.equals("id")) {
                    th.setValue("编码");
                }
                th.setRequired(true);
                th.setParamType("form");
                tableList.add(th);
                System.out.println(th.toString());
                FromAddColumn f = new FromAddColumn();
                f.setField(COLUMN_NAME);
                f.setName(REMARKS.contains(" ") ? REMARKS.split(" ")[0]: REMARKS);
                if (COLUMN_NAME.equals("id")) {
                    f.setName("编码");
                } else if ("DATETIME".equals(TYPE_NAME)) {
                    f.setDate(true);
                    f.setPlaceholder("请选择时间");
                } else if (("BIT".equals(TYPE_NAME) || "TINYINT".equals(TYPE_NAME)) && COLUMN_SIZE.equals("1")) {
                    String str[] = REMARKS.split(" ");
                    List<Map<String, String>> selectList = new ArrayList<>();
                    for (int i = 1, l = str.length; i < l; i++) {
                        String s = str[i];
                        if (s.trim().equals("") || s.trim().equals("默认")){
                            continue;
                        }
                        Map<String, String> m = new HashMap<>();
                        String[] d = s.split(":");
                        if(d.length > 1) {
                            m.put("val", d[0]);
                            m.put("label", d[1]);
                            selectList.add(m);
                        }
                    }
                    f.setSelectData(selectList);
                }
                columnList.add(f);
            }
            System.out.println("{" + json.toString().substring(1) + "}");

            System.out.println(JSON.toJSONString(tableList));
            //System.out.println(JSON.toJSONString(columnList));
        }

    }

}


